package com.arcsoft.api.system.service.impl;

import com.arcsoft.api.base.exception.CustomException;
import com.arcsoft.api.system.dto.FaceAttributesResponse;
import com.arcsoft.api.system.dto.RecognitionFaceRequest;
import com.arcsoft.api.system.dto.RegisterFaceRequest;
import com.arcsoft.api.system.entity.User;
import com.arcsoft.api.system.face.FaceManager;
import com.arcsoft.api.system.mapper.UserMapper;
import com.arcsoft.api.system.service.IUserService;
import com.arcsoft.face.*;
import com.arcsoft.face.enums.ExtractType;
import com.arcsoft.face.toolkit.ImageFactory;
import com.arcsoft.face.toolkit.ImageInfo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import groovy.util.logging.Log4j;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Base64;
import java.util.List;
@Slf4j
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Resource
    FaceManager faceManager;

    @PostConstruct
    public void init() {
        faceManager.init();
        List<User> users = this.baseMapper.selectList((new QueryWrapper<User>()));
        ArrayList<FaceFeatureInfo> faceFeatureInfos = new ArrayList<>();
        for (User user : users) {
            FaceFeatureInfo faceFeatureInfo = new FaceFeatureInfo();
            faceFeatureInfo.setSearchId(user.getId());
            faceFeatureInfo.setFaceTag(user.getUserName());
            faceFeatureInfo.setFeatureData(user.getFaceFeature());
            faceFeatureInfos.add(faceFeatureInfo);
        }
        try {
            faceManager.loadAllFace(faceFeatureInfos);
        } catch (Exception e) {
            e.printStackTrace();
            throw new CustomException("加载人脸失败");
        }
    }

    @Override
    public void registerFace(RegisterFaceRequest request) {
        try {
//            Base64.getDecoder()
//            Base64.getUrlEncoder()
//            Base64.getMimeDecoder()
            byte[] decode = Base64.getDecoder().decode(request.getPhoto().getBytes(StandardCharsets.UTF_8));
            ImageInfo imageInfo = ImageFactory.getRGBData(decode);
            //检测人脸
            ArrayList<FaceInfo> faceInfos = faceManager.detectFaces(imageInfo);
            //人脸图像质量检测，只有符合质量的图片采取提取特征值
            float quality = faceManager.imageQuality(imageInfo, faceInfos.get(0));
            if (quality>0.7){
                //提取特征值
                FaceFeature faceFeature = faceManager.extractFaceFeature(imageInfo, faceInfos.get(0), ExtractType.REGISTER);
                User user = new User();
                user.setUserName(request.getName());
                user.setFaceFeature(faceFeature.getFeatureData());
                int id = this.baseMapper.insert(user);
                FaceFeatureInfo faceFeatureInfo = new FaceFeatureInfo();
                faceFeatureInfo.setFaceTag(request.getName());
                faceFeatureInfo.setFeatureData(faceFeature.getFeatureData());
                faceFeatureInfo.setSearchId(id);
                faceManager.registerFace(faceFeatureInfo);
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new CustomException("人脸注册失败");
        }
    }

    @Override
    public String recognition(RecognitionFaceRequest request) {
        try {
            byte[] decode = Base64.getDecoder().decode(request.getPhoto().getBytes(StandardCharsets.UTF_8));
            ImageInfo imageInfo = ImageFactory.getRGBData(decode);
            //检测人脸
            ArrayList<FaceInfo> faceInfos = faceManager.detectFaces(imageInfo);
            //人脸图像质量检测，只有符合质量的图片采取提取特征值
            float quality = faceManager.imageQuality(imageInfo, faceInfos.get(0));
            if (quality>0.7){
                //提取特征值
                FaceFeature faceFeature = faceManager.extractFaceFeature(imageInfo, faceInfos.get(0), ExtractType.RECOGNIZE);
                SearchResult searchResult = faceManager.searchFace(faceFeature);
                if (searchResult.getMaxSimilar()>0.85){
                    return searchResult.getFaceFeatureInfo().getFaceTag();
                }else {
                    throw new CustomException("未识别到人脸");
                }
            }else{
                throw new CustomException("图像质量不合格");
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new CustomException("人脸识别失败");
        }
    }

    @Override
    public FaceAttributesResponse attribute(RecognitionFaceRequest request) {
        try {
            byte[] decode = Base64.getDecoder().decode(request.getPhoto().getBytes(StandardCharsets.UTF_8));
            ImageInfo imageInfo = ImageFactory.getRGBData(decode);
            //检测人脸
            ArrayList<FaceInfo> faceInfos = faceManager.detectFaces(imageInfo);
            //人脸图像质量检测，只有符合质量的图片采取提取特征值
         return   faceManager.faceAttributes(imageInfo, faceInfos.get(0));
        } catch (Exception e) {
            e.printStackTrace();
            throw new CustomException("人脸注册失败");
        }
    }
}
